package com.xxy.partnermatch.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxy.partnermatch.common.BaseResponse;
import com.xxy.partnermatch.common.DeleteRequest;
import com.xxy.partnermatch.exception.BusinessException;
import com.xxy.partnermatch.model.dto.*;
import com.xxy.partnermatch.model.entity.Team;
import com.xxy.partnermatch.model.entity.UserTeam;
import com.xxy.partnermatch.model.enums.ErrorCode;
import com.xxy.partnermatch.model.vo.TeamUserVO;
import com.xxy.partnermatch.model.vo.UserVO;
import com.xxy.partnermatch.service.TeamService;
import com.xxy.partnermatch.service.UserService;
import com.xxy.partnermatch.service.UserTeamService;
import com.xxy.partnermatch.utils.ResultUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * ClassName: TeamController
 * Package: com.xxy.partnermatch.controller
 * Description: 队伍请求Controller
 *
 * @Author 十一
 * @Create 2024/11/19 10:42
 * @Version 1.0
 */
@Tag(name = "队伍管理")     // 描述controller类的作用
@CrossOrigin(origins = {"http://localhost:3000"})
@RestController
@RequestMapping("/team")
@Slf4j
public class TeamController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;

    /**
     * 新增队伍
     *
     * @param teamAddRequest 新增队伍请求体
     * @param request        request请求对象
     * @return 新增队伍id
     */
    @Operation(summary = "新增队伍")
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取登录用户
        UserVO loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        long result = teamService.addTeam(team, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 查询队伍列表
     *
     * @param teamQuery 队伍查询请求体
     * @param request   request请求对象
     * @return 队伍列表 (脱敏)
     */
    @Operation(summary = "查询队伍列表")
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        // 1、查询队伍列表
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, isAdmin);
        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).toList();

        // 2. 判断当前用户是否已加入队伍
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        try {
            UserVO loginUser = userService.getLoginUser(request);
            queryWrapper.eq("userId", loginUser.getId());
            queryWrapper.in("teamId", teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
            // 已加入队伍的 id集合
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.forEach(teamUserVO -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(teamUserVO.getId());
                teamUserVO.setHasJoin(hasJoin);
            });
        } catch (Exception e) {
            log.error("查询队伍列表失败: ", e);
        }

        // 3、查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        if (!teamIdList.isEmpty()) {
            userTeamJoinQueryWrapper.in("teamId", teamIdList);
        }
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> {
            team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size());
        });
        return ResultUtils.success(teamList);
    }

    /**
     * 解散队伍
     *
     * @param deleteRequest 删除请求体
     * @param request       request请求对象
     * @return 是否成功解散
     */
    @Operation(summary = "解散队伍")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getLoginUser(request);
        boolean result = teamService.deleteTeam(deleteRequest.getId(), loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "解散队伍失败");
        }
        return ResultUtils.success(result);
    }

    /**
     * 修改队伍
     *
     * @param team    修改队伍信息
     * @param request request请求对象
     * @return 是否修改成功
     */
    @Operation(summary = "修改队伍")
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest team, HttpServletRequest request) {
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(team, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "修改队伍失败");
        }
        return ResultUtils.success(result);
    }

    /**
     * 根据队伍id获取指定队伍
     *
     * @param id 队伍id
     * @return 指定队伍
     */
    @Operation(summary = "根据队伍id获取指定队伍")
    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "获取指定队伍失败");
        }
        return ResultUtils.success(team);
    }

    /**
     * 查询队伍列表(分页查询)
     *
     * @param teamQuery 队伍查询请求体
     * @return 队伍列表(分页)
     */
    @Operation(summary = "查询队伍列表(分页查询)")
    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listPageTeams(TeamQuery teamQuery) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> teamPage = teamService.page(page, queryWrapper);
        return ResultUtils.success(teamPage);
    }

    /**
     * 加入队伍
     *
     * @param teamJoinRequest
     * @param request
     * @return
     */
    @Operation(summary = "加入队伍")
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "加入队伍失败");
        }
        return ResultUtils.success(result);
    }

    /**
     * 退出队伍
     *
     * @param teamQuitRequest 用户退出队伍请求体
     * @param request         request请求对象
     * @return 是否成功退出队伍
     */
    @Operation(summary = "退出队伍")
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户创建的队伍
     *
     * @param teamQuery 队伍查询请求体
     * @param request   request请求对象
     * @return 当前用户创建的队伍列表
     */
    @Operation(summary = "获取当前用户创建的队伍")
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getLoginUser(request);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVO> teamUserVOList = teamService.listTeams(teamQuery, true);
        return ResultUtils.success(teamUserVOList);
    }

    /**
     * 获取当前用户加入的队伍
     *
     * @param teamQuery 队伍查询请求体
     * @param request   request请求对象
     * @return 当前用户加入的队伍列表
     */
    @Operation(summary = "获取当前用户加入的队伍")
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getLoginUser(request);
        // 查询出所有队伍
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        // 取出不重复的队伍 id
        // teamId userId
        // 1, 2
        // 1, 3
        // 2, 3
        // ======result======
        // 1 => 2, 3
        // 2 => 3
        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        ArrayList<Long> idList = new ArrayList<>(listMap.keySet());
        teamQuery.setIdList(idList);
        List<TeamUserVO> teamUserVOList = teamService.listTeams(teamQuery, true);
        return ResultUtils.success(teamUserVOList);
    }

}
